package edu.pku.act.test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MulticastReceived {
	public void work(Handler handler) {
		InetAddress group = null;
		try {
			group = InetAddress.getByName("224.0.0.251");
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} 
        int port = 52121;
        MulticastSocket msr = null;  
        try {  
            msr = new MulticastSocket(port);   
            msr.joinGroup(group);   
            byte[] buffer = new byte[8192];  
            System.out.println("start receive from " + group+":"+port + ")");  
            while (true) {  
                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);   
                msr.receive(dp);  
                String s = new String(dp.getData(), 0, dp.getLength());   
                System.out.println("GOT:"+s);
                Message msg = new Message();
                msg.obj = s;
                handler.sendMessage(msg); 
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
  
        } finally {  
            if (msr != null) {  
                try {  
                    msr.leaveGroup(group);  
                    msr.close();   
                } catch (IOException e) {  
                }  
            }  
        }  
	}
}
